import React, { createContext, useReducer, useEffect, useState } from "react";
import quizData from "../../data/QuizData";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import query from "../../api/query";

const TestQuesContext = createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_testQues":
      return [...state, action.payload];
    case "edit_testQues": //传入题目对象
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_testQues": //传入题目_id
      return state.filter((item) => item._id !== action.payload);
  }
};

export const TestQuesProvider = ({ children }) => {
  const [testQuesLists, dispatch] = useReducer(dataReducer, []);
  const [isTestQuesLoading, setIsTestQuesLoading] = useState(false);
  const [isTestQuesError, setIsTestQuesError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsTestQuesLoading(true);
      setIsTestQuesError(false);

      try {
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/testQues", {
          headers: { Authorization: token },
        });
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsTestQuesError(true);

        console.log("初始化试题出错", err);
      }
      setIsTestQuesLoading(false);
    };
    fetchData();
  }, []);

  const addTestQues = async (testQues, callback) => {
    try {
      setIsTestQuesLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/testQues", testQues, {
        headers: { Authorization: token },
      });
      dispatch({ type: "add_testQues", payload: result.data.data });
      Alert.alert("", "添加试题成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("添加试题失败", err);
      Alert.alert("", "添加试题失败");
    }
    setIsTestQuesLoading(false);
  };

  const editTestQues = async (testQues, callback) => {
    try {
      setIsTestQuesLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.patch("/testQues/" + testQues._id, testQues, {
        headers: { Authorization: token },
      });
      dispatch({ type: "edit_testQues", payload: result.data.data });
      Alert.alert("", "试题修改成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("修改试题失败", err);
      Alert.alert("", "修改试题失败");
    }
    setIsTestQuesLoading(false);
  };

  const deleteTestQues = async (testQuesId) => {
    try {
      setIsTestQuesLoading(true);
      const token = await AsyncStorage.getItem("token");
      await query.delete("/testQues/" + testQuesId, {
        headers: { Authorization: token },
      });
      dispatch({ type: "delete_testQues", payload: testQuesId });
      Alert.alert("", "试题删除成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("删除试题失败", err);
      Alert.alert("", "删除试题失败");
    }
    setIsTestQuesLoading(false);
  };

  return (
    <TestQuesContext.Provider
      value={{
        testQuesLists: testQuesLists,
        addTestQues,
        editTestQues,
        deleteTestQues,
        isTestQuesLoading,
      }}
    >
      {children}
    </TestQuesContext.Provider>
  );
};

export default TestQuesContext;
